/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package tests;

import entities.tools.Form;
import entities.tools.Question;
import entities.users.FormSigner;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import util.ejb.FilledFormBeanInterface;
import util.ejb.FormBeanInterface;
import util.ejb.FormFillingBeanInterface;
import util.ejb.FormSignerBeanInterface;

/**
 * Test used for simulating multirequest transactional process of filling the web form
 * It is simulating following scenario:
 * Request 0 - Database is cleaned
 * Request 1 - User starts filling the form.
 * Request 2-N - Users ansfer the single question (one question per request)
 * Request N+1 - Users save the form
 * Server is reset. And the scenario described "powyżej" is done twice more times.
 * Request M - Database is cleaned.
 * Request M+1 - Users creates a form. Users cancel the filling of the form.
 * TODO: Modify the scenario by adding to more question answering request, before the filling form proccess is canceled
 * TODO: Remove clean database request just after sending a form. Clean database operation should be performed only at the first run of the script, when the session is created, and after the cancelling form request.
 * @author Marek  
 */
@WebServlet(name = "test4Servlet", urlPatterns = {"/test4"})
public class FillingTheFormInFewRequestsTest extends HttpServlet {
    @PersistenceContext(name = "test", unitName = "JEE-study-warPU")
    private EntityManager em;

    @EJB
    FormBeanInterface formBean;

    @EJB
    FormFillingBeanInterface formFillingBean;

    @EJB
    FormSignerBeanInterface formSignerBean;

    @EJB
    FilledFormBeanInterface filledFormBean;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {

            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<meta http-equiv=\"refresh\" content=\"1;URL='"+getServletContext().getContextPath()+"'\"");
            out.println("<title>Filling the form in a few requests</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Filling the form in few a requests: ansfering questions, sending the form, canceling the filling of the form.</h1>");

            HttpSession session = request.getSession(true);
            Long requestCounter = (Long) session.getAttribute("requestCounter");
            if (requestCounter == null) {
                requestCounter = new Long(0);
                session.setAttribute("requestCounter", requestCounter);
            }
            Long sendedForms = (Long) session.getAttribute("sendedForms");
            if (null == session.getAttribute("sendedForms")) {
                sendedForms = new Long(0);
                session.setAttribute("sendedForms", new Long(0));
            }
            out.println("Request number:" + requestCounter + "<br/>");
            out.println("Sended forms:" + sendedForms + "<br/>");

            System.out.println("Request number " + requestCounter);
            Form form = null;
            FormSigner formSigner = null;
            if (requestCounter == 0) {
                out.println("Force cleaning of the database.");
                List<Form> forms = formBean.getAllForms();
                for (Form tmpform : forms) {
                    formBean.forcedDeleteForm(tmpform);
                }
                List<FormSigner> formSigners = formSignerBean.getFormSigners();
                for (FormSigner tmpFormSigner : formSigners) {
                    formSignerBean.forcedDeleteFormSigner(tmpFormSigner);
                }
                session.setAttribute("requestCounter", new Long(1));
            } else if (requestCounter == 1) {
                out.println("creating a new form<br/>");
                form = formBean.createNewForm();
                formSigner = formSignerBean.createFormSigner();
                for (int x = 0; x < 15; x++) {
                    formBean.createNewQuestion(form);
                }
                session.setAttribute("formId", form.getId());
                session.setAttribute("formSignerId", formSigner.getId());
                formFillingBean.beginFillingForm(form, formSigner);
                out.println("The filling the form(id=" + form.getId() + ") - formSigner(id=" + formSigner.getId() + ") transaction has been started.<br/>");
                session.setAttribute("requestCounter", requestCounter + 1);
            } else if (requestCounter == 10) {
                session.setAttribute("requestCounter", new Long(0));
                out.println("Sending the form<br/>");
                formFillingBean.sendForm();
                session.setAttribute("requestCounter", new Long(1));
                Long tmp = (Long) session.getAttribute("sendedForms");
                session.setAttribute("sendedForms", tmp + 1);
            } else {
                form = formBean.getExistingForm((Long) session.getAttribute("formId"));
                List<Question> list = formBean.getAllQuestions(form);
                out.println("Request nr " + (requestCounter + 1) + " - answering " + (requestCounter + 1) + " question<br/>");
                String answerValue = "";
                for (int z = 0; z < requestCounter; z++) {
                    answerValue+=""+list.get(requestCounter.intValue()).getId() + ":" + z+"¶";
                }
                formFillingBean.answerQuestion(list.get(requestCounter.intValue() - 1), answerValue);
                session.setAttribute("requestCounter", requestCounter + 1);
            }

            if (sendedForms.intValue() == 3) {
                out.println("Cancelling the form. Transaction rolled back");
                out.println("Test will have been reseted in the next refresh");
                formFillingBean.cancelFormFilling();
                session.setAttribute("requestCounter", new Long(0));
                session.setAttribute("sendedForms", new Long(0));
            }

            out.println("</body>");
            out.println("</html>");
        }
    }

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
